<?php
class InstallController extends Controller {
    var $no_session = array('install', 'index', 'success');
    var $components = array('install', 'options');

    function index() {
        $this->action = 'install';
        $this->install();
    }

    function install() {
        $this->layout = 'install';
        $error_notice = null;
        // Let's check to make sure Arlicle isn't already installed.
        if ( is_arlicle_installed() ) {
            arlicle_die('<h1>'.__('Already Installed').'</h1><p>'.__('You appear to have already installed Arlicle. To reinstall please clear your old database tables first.').'</p></body></html>');
        }
        if (!empty($this->data)) {
            $username = $this->data['User']['username'];
            $password = $this->data['User']['password'];
            $password_confirm = $this->data['User']['password_confirm'];
            $email = $this->data['User']['email'];
            $site_title = $this->data['Options']['site_title'];
            $initial_data = isset($this->data['Options']['initial_data']) ? $this->data['Options']['initial_data'] : '';
            if (empty($username)) {
                $error_notice = __('ERROR: The username is empty.');
            }
            if (empty($error_notice)) {
                $username = sanitize_user($username);
                if (empty($username)) {
                    $error_notice = __('ERROR: Invalid username.');
                }
            }

            if (empty($error_notice)) {
                if (empty($password)) {
                $error_notice = __('ERROR: The password is empty.');
                }
            }

            if (empty($error_notice)) {
                if ($password != $password_confirm) {
                $error_notice = __('ERROR: The password not equal.');
                }
            }

            if (empty($error_notice)) {
                install_db();
                insert_super_user($username, $password, $email);
                mk_arlicle_dir();
                $base = str_replace('index.php', '', env('SCRIPT_NAME'));
                $site_url = 'http://' . env('HTTP_HOST') . $base;
                update_option('site_url', $site_url);
                update_option('home_url', $site_url);
                update_option('site_title', $site_title);
                update_option('site_email', $email);
                if (!empty($initial_data)) {
                    initial_data();
                }
                $this->redirect('/install/success/');
                exit();
            }
        }
        $this->set('error_notice', $error_notice);
    }

    function success() {
        $this->layout = 'install';
    }
}
?>
